package com.winit.openapi.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.oms.spi.isp.ISPOrderService;
import com.winit.oms.spi.isp.PrintLabelService;
import com.winit.oms.spi.isp.command.PrintLabelCommand;
import com.winit.oms.spi.isp.vo.ISPLabel;
import com.winit.oms.spi.vo.Label;
import com.winit.oms.spi.vo.LabelInfo;
import com.winit.oms.spi.vo.PrintLabelResult;
import com.winit.oms.spi.vo.PrintLabelResult.Result;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.DateUtil;
import com.winit.openapi.util.PDFBox4MergePDF;
import com.winit.openapi.util.ValidateUtil;
import com.winit.openapi.util.WinitLabelParser;

/**
 * 打印面单 long.yue: Change to the actual description of this class
 * 
 * @version Revision History
 * 
 * <pre>
 * Author     Version       Date        Changes
 * long.yue    1.0           2015年1月8日     Created
 * 
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "/winitLable")
public class WinitLableController extends BaseController {

    /**
     * 
     */
    private Logger            logger = LoggerFactory.getLogger(WinitLableController.class);
    @Resource
    private PrintLabelService labelService;
    @Resource
    private ISPOrderService iSPOrderService;

    public void setLabelService(PrintLabelService labelService) {
        this.labelService = labelService;
    }

    /**
     * 13、OpenAPI打印面单，获取到文件地址后用64base编码
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/query")
    public String query(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        ValidateUtil.validNotNull(json, "orderNo");
        //ValidateUtil.validMaxLength(json, "orderNo", 60);

        PrintLabelCommand labelCommand = new PrintLabelCommand();
        this.buildCommand(json, labelCommand);
        List<ISPLabel> labels = labelCommand.getiSPLabel();
        // result
        Map<String, Object> dataMap = new HashMap<String, Object>();
        List<String> files = new ArrayList<String>();
        
        List<String> trackingNoList = new ArrayList<String>();

        if (labels.size() == 1) {
            WinitLabelParser parser = new WinitLabelParser();
            LabelInfo labelInfo= labelService.printLabel(labelCommand);
            List<Label> labList = labelInfo.getLabelList();
            for (Label lab : labList) {
            	if(lab.getPrintQty() != null && lab.getPrintQty().intValue() > 1){
            		List<String> labelPath = new ArrayList<String>();
            		for (int i = 0; i < lab.getPrintQty(); i++) {
            			labelPath.add(lab.getFilePath());
					}
            		files = mergeLabels(labelPath);
            	}else{
            		
            		files.add(parser.getWinitLabelByURL(lab.getFilePath()));
            	}
            	trackingNoList.add(lab.getTrackingNo());
            }
        } else if (labels.size() > 1) {
            // 批量打印面单
            PrintLabelResult labelInfo= labelService.multilPrintLabel(labelCommand);
            List<String> labelPath = labelInfo.getLabelPath();
            files = mergeLabels(labelPath);
            dataMap.put("successCount", labelInfo.getSuccess());
            dataMap.put("failedCount", labelInfo.getFailed());
            trackingNoList = getTrackingNoList(labelInfo);
        }
        dataMap.put("files", files);
        dataMap.put("trackingNo", trackingNoList);
        responseMsg.setData(dataMap);
        return SUCCESS;
    }
    
    private List<String> getTrackingNoList(PrintLabelResult labelInfo){
        List<String> trackingNoList = new ArrayList<String>();
        List<Result> resultList = labelInfo.getResult();
        if(CollectionUtils.isNotEmpty(resultList)){
            for(Result result:resultList){
                List<Label> labelList = result.getLabelList();
                if(CollectionUtils.isNotEmpty(labelList)){
                    Label label = labelList.get(0);
                    if(label != null){
                        trackingNoList.add(label.getTrackingNo());
                    }
                }
            }
        }
        return trackingNoList;
    }
    
    /**
     * 多面单合并成一个PDF
     * @param labelPaths 面单URL
     * @return
     */
    private List<String> mergeLabels(List<String> labelPaths){
    	List<String> files  = null;
    	if(null != labelPaths && labelPaths.size() > 0) {
    		files = new ArrayList<String>();
    		PDFBox4MergePDF tool = new PDFBox4MergePDF();
    		String path = "";
    		String os = System.getProperty("os.name");
    		if (os.toLowerCase().startsWith("win")) {
    			path = ApiConstant.PATH_MERGE_PDF_WIN + DateUtil.getCurrentDate() + ".pdf";
    		} else {
    			path = ApiConstant.PATH_MERGE_PDF_LINUX + DateUtil.getCurrentDate() + ".pdf";
    		}
    		try {
    			tool.merge(labelPaths, path);
    			files.add(tool.file2Base64(path));
    		} catch (Exception e) {
    			logger.error("WinitLableController->query :error:{}", e.getLocalizedMessage());
    		} finally {
    			// 删除临时文件
    			tool.delFile(path);
    		}
    	}
    	return files;
    }
    

    /**
     * 构造打印面单对象
     * 
     * @param json
     * @param command
     */
    private void buildCommand(JSONObject json, PrintLabelCommand command) {
        if (StringUtils.isNotBlank(json.getString("orderNo"))) {
            String[] arr = json.getString("orderNo").split(",");
            if(arr.length>200){
                throw new ApiException(ErrorCode.ISP_LALBE_SIZE_ERROR);
            }
            List<ISPLabel> labels = new ArrayList<ISPLabel>();
            for (int i = 0; i < arr.length; i++) {
                if(StringUtils.isNotBlank(arr[i])){
                    ISPLabel ispLabel = new ISPLabel();
                    ispLabel.setOrderNO(arr[i]);
                    labels.add(ispLabel);
                }
            }
            command.setiSPLabel(labels);
        }
    }
    /**
     * 打印isp发货凭证
     * TODO Add comments here.
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/printISPShippingDocument")
    public String printISPOrderShippingDocument(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
            // 获取参数
            JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
            ValidateUtil.validNotNull(json, "orderNo");
            List<String> list = new ArrayList<String>();
            String[] arr = json.getString("orderNo").split(",");
            for (String str : arr) {
                list.add(str);
            }
            String pdf = iSPOrderService.printISPOrderShippingDocument(list);
            responseMsg.setData(pdf);
            return SUCCESS;
            
    }
    
}
